#include "SceneBattle.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "deprecated/CCDeprecated.h"
#include "ui/UIHelper.h"
#include "base/CCConsole.h"
#include "common/PIOStreamOperator.h"
#include "logic/LLogicScene.h"
#include <string>

USING_NS_CC;
using namespace ui;

GroupLookInfo CSceneBattle::m_BattleInfo;
CSceneBattle::SceneBaseInfo CSceneBattle::m_SceneInfo;

CSceneBattle::CSceneBattle(void)
{
	//MasterBodyNode tNode;
	for (int32_t i = 0; i != GroupCount; ++i) {
		m_TopGroup.push_back(new MasterBodyNode());
		m_DownGroup.push_back(new MasterBodyNode());
	}

	m_SelectSkill = PhysicAttack;
	m_OwnPos.m_IsBody = 0;
}


CSceneBattle::~CSceneBattle(void)
{
	for (int32_t i = 0; i != GroupCount; ++i) {
		delete m_TopGroup[i];
		delete m_DownGroup[i];
	}
}

bool CSceneBattle::init() {
	// 1. super init first
    if ( !CSceneBase::init() )
    {
        return false;
    }

    return true;
}

void CSceneBattle::onEnter() {
	cocos2d::Scene::onEnter();

	m_Battle = CSLoader::createNode("BattleScene.csb");

	auto tNode = CCocosUiHelper::seekNodeByTag(m_Battle, 7278);
	m_TopGroup.at(GroupLeft)->m_User = CCocosUiHelper::seekNodeByName(tNode, "top_u_l");
	m_TopGroup.at(GroupLeft)->m_Body = CCocosUiHelper::seekNodeByName(tNode, "top_b_l");
	m_TopGroup.at(GroupDuizhang)->m_User = CCocosUiHelper::seekNodeByName(tNode, "top_u_m");
	m_TopGroup.at(GroupDuizhang)->m_Body = CCocosUiHelper::seekNodeByName(tNode, "top_b_m");
	m_TopGroup.at(GroupRight)->m_User = CCocosUiHelper::seekNodeByName(tNode, "top_u_r");
	m_TopGroup.at(GroupRight)->m_Body = CCocosUiHelper::seekNodeByName(tNode, "top_b_r");

	tNode = CCocosUiHelper::seekNodeByTag(m_Battle, 7279);
	m_DownGroup.at(GroupLeft)->m_User = CCocosUiHelper::seekNodeByName(tNode, "down_u_l");
	m_DownGroup.at(GroupLeft)->m_Body = CCocosUiHelper::seekNodeByName(tNode, "down_b_l");
	m_DownGroup.at(GroupDuizhang)->m_User = CCocosUiHelper::seekNodeByName(tNode, "down_u_m");
	m_DownGroup.at(GroupDuizhang)->m_Body = CCocosUiHelper::seekNodeByName(tNode, "down_b_m");
	m_DownGroup.at(GroupRight)->m_User = CCocosUiHelper::seekNodeByName(tNode, "down_u_r");
	m_DownGroup.at(GroupRight)->m_Body = CCocosUiHelper::seekNodeByName(tNode, "down_b_r");

	InitSkill();

	addChild(m_Battle);

	if (IsMyGroup(m_BattleInfo.m_SecondGroupInfo)) {
		m_OwnPos.m_GroupIndex = GLSceneSecond;
		InitGroup(m_BattleInfo.m_SecondGroupInfo, m_BattleInfo.m_FirstGroupInfo, true);
	} else if (IsMyGroup(m_BattleInfo.m_FirstGroupInfo)) {
		m_OwnPos.m_GroupIndex = GLSceneFirst;
		InitGroup(m_BattleInfo.m_FirstGroupInfo, m_BattleInfo.m_SecondGroupInfo, false);
	}

	StartTimer();
	//this->scheduleUpdate();
}

void CSceneBattle::Play(uint8_t count, ReturnUseSkillInfo* info, uint8_t isEnd) {
	m_Director->getScheduler()->performFunctionInCocosThread(CC_CALLBACK_0(CSceneBattle::onPlay, this, count, info, isEnd));
}

void CSceneBattle::onExit() {
	cocos2d::Scene::onExit();
	//this->unscheduleUpdate();
}

void CSceneBattle::update(float delta) {
	cocos2d::Scene::update(delta);
}

/*
void CSceneBattle:::onOpenPack(cocos2d::Ref* pSender, cocos2d::ui::TouchEventType type) {
	switch (type)
	{
	case cocos2d::ui::TOUCH_EVENT_ENDED:
		
		break;
	}
}*/

void CSceneBattle::onPlay(uint8_t count, ReturnUseSkillInfo* info, uint8_t isEnd) {
	/*for (uint8_t i = 0; i != count; ++i) {
	m_Log << "src,group:" << (int32_t)info->m_Src.m_GroupIndex << ",index:" << (int32_t)info->m_Src.m_Index << ",body:" << (int32_t)info->m_Src.m_IsBody << "\n";
	for (uint8_t j = 0; j != info->m_PropertyCount; ++j) {
	const ChangedProperty& tProp = info->m_Property[j];
	m_Log << "property,group:" << (int32_t)tProp.m_Pos.m_GroupIndex << "," << (int32_t)tProp.m_Pos.m_Index << "," << (int32_t)tProp.m_Pos.m_IsBody
	<< "|prop:" << tProp.m_ChangedProp[ChangedHpCur] << "," << tProp.m_ChangedProp[ChangedMpCur] << "|process|" << (int)tProp.m_Process << "\n";
	}
	for (uint8_t j = 0; j != info->m_EffectCount; ++j) {
	const ChangedEffect& tEffect = info->m_Effect[j];
	m_Log << "effect_a,pos:" << (int32_t)tEffect.m_Pos.m_GroupIndex << "," << (int32_t)tEffect.m_Pos.m_Index << "," << (int32_t)tEffect.m_Pos.m_IsBody
	<< "|type:" << tEffect.m_Type << ",flag:" << (int32_t)tEffect.m_AddFlag << "\n";
	}
	info++;
	}*/
	//m_Log << "\n";
	//CCLOG("%s", m_Log);
	//m_OutLog->setString(m_Log);

	CCommonUiManager::RunProppertyBroadcastParam tParam;
	tParam.name.clear();
	tParam.flag.clear();
	tParam.startPos = cocos2d::Vec2(0, 0);
	for (uint8_t i = 0; i != count; ++i) {
		for (uint8_t j = 0; j != info->m_PropertyCount; ++j) {
			const ChangedProperty& tProp = info->m_Property[j];
			//tParam.value = tProp.m_ChangedProp;
			cocos2d::Node* tNode = getNodeByPos(tProp.m_Pos);
			NodeData* tData = (NodeData*)tNode->getUserData();

			tParam.runNode = tNode;
			if (tProp.m_Pos.m_IsBody == 0) {
				CCLOG("master~~~%s~~%d,%d,%d---%d~~~%d", __FUNCTION__, tProp.m_Pos.m_GroupIndex, tProp.m_Pos.m_Index, tProp.m_Pos.m_IsBody, tData->m_CommonData->m_Info.m_MasterProp[ChangedHpCur], tProp.m_ChangedProp[ChangedHpCur]);
				tParam.value = tData->m_CommonData->m_Info.m_MasterProp[ChangedHpCur] - tProp.m_ChangedProp[ChangedHpCur];
				tData->m_CommonData->m_Info.m_MasterProp[ChangedHpCur] = tProp.m_ChangedProp[ChangedHpCur];
			} else {
				CCLOG("body~~~%s~~%d,%d,%d---%d~~~%d", __FUNCTION__, tProp.m_Pos.m_GroupIndex, tProp.m_Pos.m_Index, tProp.m_Pos.m_IsBody, tData->m_CommonData->m_Info.m_BodyProp[ChangedHpCur], tProp.m_ChangedProp[ChangedHpCur]);
				tParam.value = tData->m_CommonData->m_Info.m_BodyProp[ChangedHpCur] - tProp.m_ChangedProp[ChangedHpCur];
				tData->m_CommonData->m_Info.m_BodyProp[ChangedHpCur] = tProp.m_ChangedProp[ChangedHpCur];
			}
			if (tParam.value != 0)
				m_UiManager->RunPropertyBroadcast(tParam, CCommonUiManager::NQIPropertyBroadcastBattle);
		}
		info++;
	}

	if (isEnd) {
		//m_SceneManager->popScene();
	} else {
		StartTimer();
	}
}

void CSceneBattle::onSelectNode(cocos2d::Ref* pSender, cocos2d::ui::TouchEventType type) {
	switch (type)
	{
	case cocos2d::ui::TOUCH_EVENT_ENDED:
		cocos2d::Node* tSender = (cocos2d::Node*)pSender;
		cocos2d::Node* tDataP = (cocos2d::Node*)tSender->getUserData();
		NodeData* tData = (NodeData*)tDataP->getUserData();
		if (nullptr == tData) {
			CCLOG("error|select|node|user|data");
			return;
		}

		UseSkillInfo tSkill;
		tSkill.m_Index = m_SkillList->getCurSelectedIndex() + PhysicAttack;
		tSkill.m_Src = m_OwnPos;
		tSkill.m_Dest = tData->m_Pos;

		CTLLogicScene tLogicScene;
		tLogicScene.PersonUseSkill(m_SceneInfo, tSkill);
		break;
	}
}

bool CSceneBattle::IsMyGroup(const OneGroupLookInfo& group) {
	const UserId_t& tUid = m_LogicData->GetOneself()->GetBaseInfo().m_Uid;
	if (group.m_IsGroup) {
		for (int32_t i = 0; i != MAX_PERSON_NUMBER; ++i) {
			const MasterBattleLookInfo& tMaster = group.m_Masters[i];
			if (tMaster.m_Uid == tUid) {
				m_OwnPos.m_Index = i;
				return true;
			}
		}
	} else {
		const MasterBattleLookInfo& tMaster = group.m_Masters[GroupDuizhang];
		if (tMaster.m_Uid == tUid) {
			m_OwnPos.m_Index = GroupDuizhang;
			return true;
		}
	}

	return false;
}

void CSceneBattle::InitGroup(const OneGroupLookInfo& my, const OneGroupLookInfo& other, bool myIsSecend) {
	auto SetMBNodeFunc = [&](const MasterBattleLookInfo& master, MasterBodyNode* node, CCommonUiManager::BattleAnimalParam& param)->void {
		ui::ImageView *tSprite = nullptr;
		if (CGLAinmalLow::IsAnimal(master.m_Type)) {
			param.isUser = true;
			cocos2d::Node* tAnimal = m_UiManager->GetBattleAnimal(param);
			node->m_User->addChild(tAnimal);
			tAnimal->setAnchorPoint(cocos2d::Vec2(0.5, 0.5));
			initAnimal(tAnimal, master);

			if (master.m_BodySize != 0) {
				const AnimalLookInfo& tBody = master.m_Body;
				if (CGLAinmalLow::IsAnimal(tBody.m_Type)) {
					param.isUser = false;
					cocos2d::Node* tAnimal = m_UiManager->GetBattleAnimal(param);
					node->m_Body->addChild(tAnimal);
					tAnimal->setAnchorPoint(cocos2d::Vec2(0.5, 0.5));
					initAnimal(tAnimal, tBody);
				}

			}
		}
	};

	auto SetNodeInfo = [&](const MasterBattleLookInfo& master, MasterBodyNode* node, uint8_t group, uint8_t index, CCommonUiManager::BattleAnimalParam& param)->void{
		SetMBNodeFunc(master, node, param);
		node->m_CData.m_Info = master;

		if (nullptr != node->m_User) {
			node->m_UData.m_Pos.SetInfo(group, index, 0);
			node->m_User->setUserData(&node->m_UData);
		}

		if (nullptr != node->m_Body) {
			node->m_BData.m_Pos.SetInfo(group, index, 1);
			node->m_Body->setUserData(&node->m_BData);
		}
	};

	CCommonUiManager::BattleAnimalParam tParam;
	tParam.isUp = false;
	if (my.m_IsGroup) {
		for (int32_t i = 0; i != MAX_PERSON_NUMBER; ++i) {
			tParam.index = (GroupIndex)i;
			const MasterBattleLookInfo& tMaster = my.m_Masters[i];
			MasterBodyNode* tNode = m_DownGroup.at(i);

			uint8_t tGroup = myIsSecend?GLSceneSecond:GLSceneFirst;
			SetNodeInfo(tMaster, tNode, tGroup, i, tParam);
		}
	} else {
		tParam.index = GroupDuizhang;
		const MasterBattleLookInfo& tMaster = my.m_Masters[GroupDuizhang];
		MasterBodyNode* tNode = m_DownGroup.at(GroupDuizhang);

		uint8_t tGroup = myIsSecend?GLSceneSecond:GLSceneFirst;
		SetNodeInfo(tMaster, tNode, tGroup, GroupDuizhang, tParam);
	}

	tParam.isUp = true;
	if (other.m_IsGroup) {
		for (int32_t i = 0; i != MAX_PERSON_NUMBER; ++i) {
			tParam.index = (GroupIndex)i;
			const MasterBattleLookInfo& tMaster = other.m_Masters[i];
			MasterBodyNode* tNode = m_TopGroup.at(i);

			uint8_t tGroup = myIsSecend?GLSceneFirst:GLSceneSecond;
			SetNodeInfo(tMaster, tNode, tGroup, i, tParam);
		}
	} else {
		tParam.index = GroupDuizhang;
		const MasterBattleLookInfo& tMaster = other.m_Masters[GroupDuizhang];
		MasterBodyNode* tNode = m_TopGroup.at(GroupDuizhang);

		uint8_t tGroup = myIsSecend?GLSceneFirst:GLSceneSecond;
		SetNodeInfo(tMaster, tNode, tGroup, GroupDuizhang, tParam);
	}
}

void CSceneBattle::InitSkill() {
	CILogicPerson* tOneself = m_LogicData->GetOneself();
	BattleSkill& tSkill = tOneself->GetSkill().m_BattleSkill;

	m_SkillList = m_UiManager->InitSkillView(CCocosUiHelper::seekNodeByTag(m_Battle, 71), &tSkill.AllSkill[PhysicAttack], PhysicAttack, BattleSkillCount, m_SkillListItems);
}

void CSceneBattle::initAnimal(cocos2d::Node* node, const AnimalLookInfo& info) {
	/*ui::ImageView *tSprite = ui::ImageView::create("Huchey_png/huchey_head.png");
	tSprite->setTouchEnabled(true);
	tSprite->addTouchEventListener(this, toucheventselector(CSceneBattle::onSelectNode));*/

	cocos2d::ui::Text* tName = (cocos2d::ui::Text*)CCocosUiHelper::seekNodeByTag(node, 226);
	tName->setString(info.m_Name);
	cocos2d::ui::LoadingBar* tValue = (cocos2d::ui::LoadingBar*)CCocosUiHelper::seekNodeByTag(node, 225);

	ui::ImageView * tUser = (ui::ImageView *)CCocosUiHelper::seekNodeByTag(node, 58);

	tUser->setUserData(node->getParent());
	tUser->setTouchEnabled(true);
	tUser->addTouchEventListener(this, toucheventselector(CSceneBattle::onSelectNode));
}

void CSceneBattle::TimerUpdate(float delta) {
	std::string tStrTimer;
	ui::Text* tTimer = (ui::Text*)CCocosUiHelper::seekNodeByTag(this, 529);
	if (m_Timer == 0) {
		StopTimer();
		tTimer->setString(tStrTimer);
		return;
	}

	--m_Timer;
	tStrTimer << m_Timer;
	tTimer->setString(tStrTimer);
}

void CSceneBattle::StartTimer() {
	m_Timer = 10;

	std::string tStrTimer;
	ui::Text* tTimer = (ui::Text*)CCocosUiHelper::seekNodeByTag(this, 529);
	tStrTimer << m_Timer;
	tTimer->setString(tStrTimer);

	schedule(schedule_selector(CSceneBattle::TimerUpdate), 1.0f);
	scheduleUpdate();
}

void CSceneBattle::StopTimer() {
	unschedule(schedule_selector(CSceneBattle::update));
}

cocos2d::Node* CSceneBattle::getNodeByPos(const BattlePosition& pos) {
	VecMBNode_t* tNodes = nullptr;
	if (m_OwnPos.m_GroupIndex == pos.m_GroupIndex)
		tNodes = &m_DownGroup;
	else
		tNodes = &m_TopGroup;

	if (pos.m_IsBody == 0)
		return tNodes->at(pos.m_Index)->m_User;
	else
		return tNodes->at(pos.m_Index)->m_Body;
}
